/**
 * May 12, 2014 1:33:04 PM
 */
package elitech.vietnam.copyweatherfashion.config;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.util.Log;
import elitech.vietnam.copyweatherfashion.location.GeoAddress;
import elitech.vietnam.copyweatherfashion.location.GeoResults;
import elitech.vietnam.copyweatherfashion.location.MyLocation;

/**
 * @author Cong
 * 
 */
public class Utilities {

	public static String getPriceCode() {
		String[] pricecode = { " $", " đ", " 원", " ¥" };
		String[] countrycd = { "US", "VN", "KR", "CN" };
		for (int i = 0; i < pricecode.length; i++)
			if (countrycd[i].equals(Const.COUNTRYCODE))
				return pricecode[i];
		return "";
	}

	public static Drawable getTabDrawable(Context context, int selected, int normal) {
		StateListDrawable drawable = new StateListDrawable();
		drawable.addState(new int[] { android.R.attr.state_selected }, context.getResources().getDrawable(selected));
		drawable.addState(new int[] { android.R.attr.state_enabled }, context.getResources().getDrawable(normal));
		return drawable;
	}

	public static String md5(String message) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] array = md.digest(message.getBytes("CP1252"));
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < array.length; ++i) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).toLowerCase(Locale.US).substring(1, 3));
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {

		} catch (UnsupportedEncodingException e) {

		}
		return null;
	}
	
	public static int getImageRotation(String path) {
		ExifInterface ei;
		try {
			ei = new ExifInterface(path);
		} catch (IOException e) {
			e.printStackTrace();
			return 0;
		}
		int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
				ExifInterface.ORIENTATION_NORMAL);
		int rotate = 0;
		switch (orientation) {
		case ExifInterface.ORIENTATION_ROTATE_90:
			rotate = 90;
			break;
		case ExifInterface.ORIENTATION_ROTATE_180:
			rotate = 180;
			break;
		case ExifInterface.ORIENTATION_ROTATE_270:
			rotate = 270;
			break;
		// etc.
		default:
			break;
		}
		return rotate;
	}
	
	public static boolean createScaledImage(String src, String des, int desSize) {
		try {
			Options options = new Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(src, options);
			int imageHeight = options.outHeight;
			int imageWidth = options.outWidth;

			float scale = ((float) ((imageWidth > desSize) ? desSize
					: imageWidth) / ((float) imageWidth));
			int rotate = getImageRotation(src);

			Bitmap bitmap = BitmapFactory.decodeFile(src);
			if (scale > 0) {
				imageHeight *= scale;
				imageWidth *= scale;
				bitmap = Bitmap.createScaledBitmap(bitmap, imageWidth,
						imageHeight, false);
			}
			if (rotate != 0) {
				Matrix matrix = new Matrix();
				matrix.postRotate(rotate);
				bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
						bitmap.getHeight(), matrix, true);
			}

			FileOutputStream out = new FileOutputStream(des);
			bitmap.compress(Bitmap.CompressFormat.JPEG,
					Const.IMAGE_COMPRESSION, out);
			out.close();
			bitmap.recycle();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public static String downloadImage(Context context, String url, String destination) {
		InputStream is = null;
		OutputStream os = null;
		try {
			is = context.getContentResolver().openInputStream(Uri.parse(url));
			os = new FileOutputStream(new File(destination));
			byte[] buffer = new byte[1024];
			int byteread;
			while ((byteread = is.read(buffer)) != -1) {
				os.write(buffer, 0, byteread);
			}
			is.close(); os.flush(); os.close();
			return destination;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static String getAutoLanguageCode() {
		if (Const.COUNTRYCODE.equals("VN")) {
			return "vi";
		}
		if (Const.COUNTRYCODE.equals("US")) {
			return "en";
		}
		if (Const.COUNTRYCODE.equals("KR")) {
			return "ko";
		}
		if (Const.COUNTRYCODE.equals("CN")) {
			return "zh";
		}
		return "en";
	}
	

	public static String getRegistrationId(Context context) {
		final SharedPreferences prefs = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
		String registrationId = prefs.getString(Const.PROPERTY_REG_ID, "");
		if (registrationId.length() == 0) {
			Log.i("GCM", "Registration not found.");
			return "";
		}
		
		int registeredVersion = prefs.getInt(Const.PROPERTY_APP_VERSION, Integer.MIN_VALUE);
		int currentVersion = Utilities.getAppVersion(context);
		if (registeredVersion != currentVersion) {
			Log.i("GCM", "App version changed.");
			return "";
		}
		return registrationId;
	}

	public static void storeRegistrationId(Context context, String regId) {
		final SharedPreferences prefs = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
		int appVersion = Utilities.getAppVersion(context);
		Log.i("GCM", "Saving regId on app version " + appVersion);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(Const.PROPERTY_REG_ID, regId);
		editor.putInt(Const.PROPERTY_APP_VERSION, appVersion);
		editor.commit();
	}

	public static int getAppVersion(Context context) {
		try {
			PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			// should never happen
			throw new RuntimeException("Could not get package name: " + e);
		}
	}

	public static String getLocality(MyLocation location) {
		if (location.GeoObject == null || location.GeoObject.Results.isEmpty())
			return "";
		GeoResults res = location.GeoObject.Results.get(0);
		for (GeoAddress address : res.AddressComponents) {
			if (address.types.get(0).equals("administrative_area_level_2")
					|| address.types.get(0).equals("administrative_area_level_1")
							|| address.types.get(0).equals("country"))
				return address.long_name;
		}
		return "";
	}
}
